package com.ad.backstage.common.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * Cos上传工具
 */
public class CosUploadUtils {

    //用户身份信息（secretId, secretKey）---- 腾讯云
    private final static String secretId = "AKIDDCy2rSJ2yexA8ssUgjX6Wnyxuc6wgYWk";
    private final static String secretKey = "IK8hFoAPTKwNgqkPp0wc1sc8QaWK1Vs1";
    //区域----广州
    private final static String REGION = "ap-guangzhou";
    //APPID
    private final static String APPID = "1301247723";


    /**
     * 上传文件
     * @param bucketName 存储桶名称---建议小写英文单词字母,符合业务意义 如：cover
     * @param objKeyName 对象键盘---建议前缀引用存储桶名称 如 cover/xxx.jpg
     * @param file       资源文件
     * @return 资源访问路径
     */
    public static String uploadFile(String bucketName, String objKeyName, MultipartFile file){
        //获取cos客户端
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(REGION);
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosClient = new COSClient(cred, clientConfig);
        //存储桶名称，格式：BucketName-APPID
        String bucket = bucketName + "-" + APPID;
        //判断存储桶是否存在(不存在则创建存储桶)
        if(!cosClient.doesBucketExist(bucket)){
            //创建存储桶
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
            // 设置 bucket 的权限
            createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
            Bucket bucketResult = cosClient.createBucket(createBucketRequest);

        }
        File f = transferToFile(file);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, objKeyName, f);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        //examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/folder/picture.jpg
        return bucket + ".cos." + REGION + ".myqcloud.com/" + objKeyName;
    }


    private static File transferToFile(MultipartFile multipartFile) {
        //选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file=File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 资源名称生成规则
     * @param length
     * @return
     */
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

}
